package com.wanhe.base.model.holder;


import com.wanhe.base.model.disgn.CatalogViewModel;
import com.wanhe.base.model.disgn.PageViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 用于管理设计器数据的管理类
 * Created by 陈德基 on 2016/8/17.
 */
public class DesignDataHolder {
    private static DesignDataHolder ourInstance;
    private ScheduledExecutorService server;

    public static DesignDataHolder getInstance() {
        if (ourInstance == null) {
            ourInstance = new DesignDataHolder();
        }
        return ourInstance;
    }

    private DesignDataHolder() {
    }


    private boolean isDataLoading;
    private List<CatalogViewModel> catalogViewModels = new ArrayList<>();
    private List<PageViewModel> pageViewModels = new ArrayList<>();


    public List<CatalogViewModel> getCatalogViewModels() {
        return catalogViewModels;
    }

    public List<PageViewModel> getPageViewModels() {
        return pageViewModels;
    }

    public boolean isDataLoading() {
        return isDataLoading;
    }

    public void setDataLoading(boolean dataLoading) {
        isDataLoading = dataLoading;
    }

    /**
     * 查看数据是否准备好了，可以跳入到main
     */
    public void startExecutorJ2Main() {
        if (isDataLoading) {
            if (listener != null) {
                listener.dataLoading();
            }
        } else {
            if (server != null){
                server.shutdownNow();
            }
            if (listener != null) {
                listener.loaded();
            }
        }

        if (server == null) {
            server = Executors.newSingleThreadScheduledExecutor();
            server.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    if (!isDataLoading){
                        server.shutdownNow();
                        if (listener != null){
                            listener.loaded();
                        }
                    }
                }
            }, 2, 2, TimeUnit.SECONDS);
        }
    }

    public interface OnDataReadyListener {
        void dataLoading();

        void loaded();
    }

    private OnDataReadyListener listener;

    public void setListener(OnDataReadyListener listener) {
        this.listener = listener;
    }

    public void release() {
        ourInstance = null;
        listener = null;
    }
}
